import React, { Component } from 'react'
import ProductStyle from '../../product/product.module.sass'

import MonthTable from '../common_table/month_table'
import RiskTable from '../common_table/risk_table'

import CorrelationTable from '../common_table/correlation_table'
import BarCharts from '../charts/bar'
import LineCharts from '../charts/line'
import AreaChart from '../charts/area'
import CommonBar from '../charts/common_bar'
import { axios } from '../../../Utils/index'
import url from 'url'
import cookie from 'js-cookie'
import { message, Select } from 'antd'
import { _getRankingData } from '../../../apis'
import shareHeader from './shareHeader'
import RankingTable from '../common_table/ranking_table'
import CommontHeaders from '../details/detail_common_header'
import echarts from 'echarts'

import AddModal from '../add_product/add_product_modal'
import WrapperHeader from './wrapper_header'

import { linesOptions, chartsColors, areasOptions, areaColors, barsOptions, correlationsOption } from '../../../Utils/charts_config/charts_config'

const { Option } = Select
export default class Performance extends Component {
    constructor (...props) {
        super(...props)

        this.state = {
        }
    }
    addModal () {
      this.refs.addModals._showModal()
    }

    async _initRateRisk () {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/product/getRiskIndicator',
            method: 'POST',
            data: JSON.stringify({
                fundId: query.id,
                token: cookie.get('token'),
                interval: 'year',
                benchMarkId: '',
                corId: ''
            })
        })

            message.destroy()
            if (!data.hasOwnProperty('status')) {
                message.info('接口获取数据失败')
                return
            }

            this.setState({loading: false})
            if (data.status !== 'success') {
                message.info(data.errorReason)
                return
            }
            if (!data.hasOwnProperty('result')) {
                message.info('接口获取数据失败')
                return
            }

            let result = data.result
            if (data.status === 'success') {
                return result
            } else {
                message.error('获取数据失败')
            }

    }

    async _historyRate () {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/product/monthReturn',
            method: 'POST',
            data: JSON.stringify({
                fund_id: query.id,
                token: cookie.get('token')
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }
        
        let result = JSON.parse(data.result)
        if (result.result === 'success') {
            return result.product
        } else {
            message.error('获取数据失败')
        }

    }

    async _weekRate () {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/product/weekReturn',
            method: 'POST',
            data: JSON.stringify({
                fund_id: query.id,
                compare_fund_id: 'JR000028',
                beginTime: '971107200',
                endTime: '1602259200',
                token: cookie.get('token')
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result = JSON.parse(data.result)
        if (result.result === 'success') {
            return result
        } else {
            message.error('获取数据失败')
        }

    }

    async _cascaderTags () {
        const data = await axios({
            url: '/api/hszcpz/product/findAllProduct',
            method: 'POST',
            data: JSON.stringify({
                token: cookie.get('token')
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result = JSON.parse(data.result)
        
        if (result.result === 'success') {
            const fetchData = result.product
            
            let map = {}, dest = []
            fetchData.forEach(item => {
                // if (!map[item.c_cor_name_level1]) {
                //     dest.push({value: item.c_cor_name_level1, label: item.c_cor_name_level1, children: [{value: item.c_cor_name_level2, label: item.c_cor_name_level2}]})
                //     map[item.c_cor_name_level1] = item.c_cor_name_level1
                // } else {
                //     for(let i = 0; i < dest.length; i++) {
                //         let nextItem = dest[i]
                //         if (nextItem.value === item.c_cor_name_level1) {
                //             nextItem.children.push({value: item.c_cor_name_level2, label: item.c_cor_name_level2})
                //         }
                //     }
                // }

                if (!map[item.parent_name]) {
                    let children = []
                    item.contrastProduct.forEach(item => {
                        children.push({
                            value: item.benchmark_id,
                            label: item.benchmark_name
                        })
                    })
                    dest.push({
                        value: item.parent_name,
                        label: item.parent_name,
                        children: children
                    })

                    map[item.parent_name] = item.parent_name
                }
            })

            return dest

        } else {
            message.error('获取数据失败')
        }
    }

    async _correlation () {
        const { query } = url.parse(window.location.href, true)
        const data = await axios({
            url: '/api/hszcpz/product/productCorrelation',
            method: 'POST',
            data: JSON.stringify({
                fund_id: query.id,
                c_interval: 'year',
                c_cor_ids: ['000300.SH', '000905.SH', '000016.SH', '000906.SH', '000001.SH', '399006.SZ', 'NH0100.NHF'],
                token: cookie.get('token')
            })
        })

        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        this.setState({loading: false})
        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        if (!data.hasOwnProperty('result')) {
            message.info('接口获取数据失败')
            return
        }

        let result = JSON.parse(data.result)
        if (result.result === 'success') {
            return result.productCorrelations
        } else {
            message.error('获取数据失败')
        }
    }

   async componentDidMount () {
        // console.log(this.refs.addModals)
        // this.refs.addModals._showModal()
        // await this._exportAndDownload()
        await this._detailsRanking()
        this._cascaderTags()
        const { query } = url.parse(window.location.href, true)
        const axiosParams = { fundIds: query.id, startLine: 0, dateRange: '2018-12-01:2019-12-01'}
        let loneOption = null
        let areOptions = null
        let valueOption = []

        const weekOpt = await this._weekRate()

        this.setState({weekOpt})
    
        if (this.state.weekOpt && weekOpt.resMap) {
            let { weekOpt } = this.state
            let result = weekOpt
            weekOpt = result.resMap
            
            const weekKeys = []
            let weekValue = []
            weekOpt.forEach((item, index) => {
                if (index === 0) {
                    weekValue.push({
                        name: result.fundName,
                        type: 'bar',
                        data: [],
                        barWidth: '40px',
                        itemStyle: {
                            normal: {
                                color: chartsColors[index + 3],
                                barBorderRadius: [8, 8, 8, 8],
                            }
                        }
                    })
                } else {
                    weekValue.push({
                        name: result.compareFundName,
                        type: 'bar',
                        data: [],
                        barWidth: '40px',
                        itemStyle: {
                            normal: {
                                color: chartsColors[index + 3],
                                barBorderRadius: [8, 8, 8, 8],
                            }
                        }
                    })
                }

            })

            Object.keys(weekOpt[0]).forEach((item, index) => {
                weekKeys[index] = item
                weekValue[0].data[index] = weekOpt[item]
            })

            weekOpt.forEach((item, index) => {
                weekKeys.forEach((items, indexs) => {
                    weekValue[index].data[indexs] = item[items]
                })
            })

            barsOptions.tooltip.axisPointer.lineStyle.width = 100
            barsOptions.xAxis[0].data = weekKeys
            barsOptions.series = weekValue
            barsOptions.title = {
                bottom: 0,
                subtextStyle: {
                  color: '#ccc'
                },
                subtext: '注：周收益率分布：通过将周度收益率平均分成 10 档（范围-100% 到100%，每隔 20% 一档，将最 大收益绝对值归 100%，其他收益率归入-100% 到100% 范围内），根据每档收益情况进行数量汇总，计算各档位数量占比。'
            }
        }

        if (this.props.hasOwnProperty('_getReturnCal')) {
            loneOption = await this.props._getReturnCal(axiosParams)
        }
        if (this.props.hasOwnProperty('_getDrawdownCal')) {
            areOptions = await this.props._getDrawdownCal(axiosParams)
        }

        let xData = []
        if (loneOption && typeof loneOption === 'object') {
            let keys = Object.keys(loneOption)
            // console.log(loneOption)
            //  xData = loneOption.hasOwnProperty(keys[0]) ? loneOption[keys[0]].x_axis : []
             xData = loneOption.hasOwnProperty(keys[0]) ? loneOption[keys[0]].x_axis : []
             keys.forEach((item, index) => {
                linesOptions.legend.data.push(item)
                valueOption.push({
                    name: item,
                    type: 'line',
                    symbol: false,
                    showSymbol: false,
                    symbolSize: 0,
                    lineStyle: {
                        normal: {
                            shadowColor: 'rgba(0, 0, 0, 0.2)',
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                            shadowBlur: 5
                        }
                    },
                    itemStyle: {
                        normal: {
                            color: chartsColors[index],
                        }
                    },
                    data: loneOption[item].y_axis || []
                })
            })
        }
        let areaX = []
        if (areOptions && typeof areOptions === 'object') {
            // console.log(areOptions, '------')
            let keys = Object.keys(areOptions)
            areaX = areOptions.hasOwnProperty(keys[0]) ? areOptions[keys[0]].x_axis : []

            let areaSeries = []
            areasOptions.dataZoom[0].width = 0 
            areasOptions.dataZoom[0].height = 0
            areasOptions.dataZoom[1] = {width: 0, height: 0}

            keys.forEach((item, index) => {
                areasOptions.legend.data.push(item)
                areaSeries.push({
                    name: item,
                    type: 'line',
                    symbol: false,
                    symbolSize: 0,
                    lineStyle: {
                        normal: {
                            shadowColor: 'rgba(0, 0, 0, 0.2)',
                            shadowOffsetY: 2,
                            shadowOffsetX: 2,
                            shadowBlur: 5
                        }
                    },
                    areaStyle: {
                        color: areaColors[index],
                        opacity: 1
                    },
                    itemStyle: {
                        normal: {
                            color: chartsColors[index],
                        }
                    },
                    data: areOptions[item].y_axis || []
                })
            })

            areasOptions.xAxis[0].data = areaX
            areasOptions.series = areaSeries
        }

        let correlationData = await this._correlation()

        if (correlationData) {
            let series = [
                {
                    type: 'bar',
                    data: [],
                    barWidth: '30px',
                    itemStyle: {
                        normal: {
                            color: '#fea062',
                            barBorderRadius: [8, 8, 8, 8],
                        }
                    }
                }
            ]
            let seriesValue = []
            let xData = []

            correlationData.forEach((item) => {
                if (item) {
                    seriesValue.push(item.nCorrelation)
                    xData.push(item.fundName)
                }
            })

            series[0].data = seriesValue
            correlationsOption.series = series
            correlationsOption.xAxis[0].data = xData
            correlationsOption.yAxis[0].min = -100
            correlationsOption.yAxis[0].max = 100
        }


        if (xData && xData.length > 0) {
            linesOptions.xAxis[0].data = xData
            linesOptions.series = valueOption
        }

        this.refs.lineChart.setOptions(linesOptions)

        this.refs.weekCharts.setBar(barsOptions)

        this.refs.areaChart.setOptions(areasOptions)

        this.refs.correlation.setOptions(correlationsOption)


        const Chart_rate = document.getElementById('lineChart')
        const Chart_area = document.getElementById('areaCharts')
        const areaContext = echarts.init(Chart_area)
        const rateContext = echarts.init(Chart_rate)
        rateContext.on('dataZoom', (e) => {
            // console.log(e)
            const batch = e.batch
            if (batch) {
                batch.forEach((item, index) => {
                    areaContext.dispatchAction({
                        type: 'dataZoom',
                        dataZoomIndex: index,
                        start: item.start,
                        end: item.end
                    })
                })
            } else {
                areaContext.dispatchAction({
                    type: 'dataZoom',
                    start: e.start,
                    end: e.end
                })
            }
            
        })

    }


    noCheckHeader = (title) => {
        return (
            <div className='clear-fix charts_nav_header'>
                <div className='float_left'>
                    <strong className={`charts_title chart_item_title`}>{title}</strong>
                </div>
                <div className='float_right'>
                    <span onClick={this.exprotWord.bind(this)} className='iconfont echarts_exports iconCombinedShape'></span>
                </div>
            </div>
        )
    }

    async exprotWord () {
        const dataBase = this.refs.lineChart.getContext()
        const baseData = this.refs.areaChart.getContext()
        let wordOptions = []
        wordOptions.push({
            moduleName: '收益走势图',
            moduleContent: [{
            textInfo: {
                leftTop: '',
                rightTop: ''
            },
            chartBase64: dataBase
        }]})

        wordOptions.push({
            moduleName: '回撤走势图',
            moduleContent: [{
            textInfo: {
                leftTop: '',
                rightTop: ''
            },
            chartBase64: baseData
        }]})

        let data = await axios({
            method: 'POST',
            url: '/api/hszcpz/exportWord/produceProductWordFile',
            data: JSON.stringify({
                token: cookie.get('token'),
                requestData: wordOptions
            })
        })

        if (data.status === 'success') {
            try {
                let json = JSON.parse(data.result)
                // console.log(json)
                if (json.status === 'success') {
                    const url = `http://192.168.1.51:8090/netFilter/hszcpz/exportWord/exportProductWordFile?token=${cookie.get('token')}&fileName=${json.fileName}&fileDate=${json.fileDate}`
                    window.location.href = url
                }
            } catch (err) {
                console.log(err)
                message.error('解析出错')
            }

        } else {
            message.info('获取数据失败')
        }
    }

    rankingHeader = () => {
        return (
            <div className='clear-fix charts_nav_header'>
                <div className='float_left'>

                </div>
                <div className='float_right'>
                    <span onClick={this.exprotWord.bind(this)} className='iconfont echarts_exports iconCombinedShape'></span>
                </div>
            </div>
        )
    }

    async _detailsRanking (type = 1) {
        let { query } = url.parse(window.location.href, true)
        let params = {
            token: cookie.get('token'),
            fund_id: query.id,
            c_rank_type: type
        }
        const data = await _getRankingData(params)
        
        message.destroy()
        if (!data.hasOwnProperty('status')) {
            message.info('接口获取数据失败')
            return
        }

        if (data.status !== 'success') {
            message.info(data.errorReason)
            return
        }
        let result = JSON.parse(data.result)
        let dataList = result.yearRankings
        if (dataList.length > 0) { 
            return dataList
        }
    }


    render () {
        const productName = window.localStorage.getItem('productName')
        return (
            <div className={ProductStyle.charts_items_list}>
                <div className={ProductStyle.charts_item_bg}>
                 <CommontHeaders _addModal={this.addModal.bind(this)} _cascaderTags={this._cascaderTags.bind(this)} ></CommontHeaders>
                </div>
                <div className={ProductStyle.charts_item_bg}>
                    {shareHeader('收益走势图', true, this.exprotWord.bind(this))}
                    <LineCharts idName={'lineChart'} ref='lineChart' />
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('回撤走势图')}
                    <AreaChart ref='areaChart' idName='areaCharts' />
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('收益-风险指标')}
                    <div className='mt_20'>
                        <RiskTable productName={productName} _initRateRisk={this._initRateRisk.bind(this)} />
                    </div>
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('月度收益率')}
                    <div className='mt_20'>
                        <MonthTable _historyRate={this._historyRate.bind(this)} />
                    </div>
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('周收益率分布')}
                    <BarCharts ref='weekCharts' />
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20 clear-fix`}>
                    {this.noCheckHeader('产品相关性')}
                    <div className={`float_left ${ProductStyle.charts_correlation}`}>
                        <CommonBar idName='correlationCharts' ref='correlation' />
                    </div>
                    <div className={`float_left ${ProductStyle.table_correlation} mt_10`}>
                        <CorrelationTable />
                    </div>
                </div>

                <div className={`${ProductStyle.none_bg} mt_20 clear-fix`}>
                    <div className={`float_left ${ProductStyle.history_list}`}>
                    <div className={ProductStyle.none_bg_wrapper}>
                        <WrapperHeader title={`历史投资能力`} iconStatus={true}></WrapperHeader>
                        <div className={`mt_10`}></div>
                        <RankingTable dataList={[]} />
                    </div>
                </div>
                <div className={`float_right ${ProductStyle.ranking_list}`}>
                    <div className={ProductStyle.none_bg_wrapper}>
                        <WrapperHeader title={`历年排名`} iconStatus={true}>
                            <div className={`float_right`}>
                                <Select style={{width: '140px'}} placeholder='全市场' className={`${ProductStyle.selection_wrapper}`}>
                                    <Option value="2">全市场</Option>
                                    <Option value="3">汇升核心池投顾</Option>
                                    <Option value="1">同策略排名</Option>
                                </Select>
                            </div>
                        </WrapperHeader>
                        <RankingTable dataList={this._detailsRanking()} />
                    </div>
                </div>
                </div>

                {/* <div className={`${ProductStyle.none_bg} mt_20 clear-fix`}>
                    <div className={`float_left ${ProductStyle.history_list}`}>
                        <div className={ProductStyle.none_bg_wrapper}>
                            {SetSelectHeader('历史投资能力')}
                            <HistoryTable />
                        </div>
                    </div>
                    <div className={`float_right ${ProductStyle.ranking_list}`}>
                        <div className={ProductStyle.none_bg_wrapper}>
                            {this.rankingHeader('')}
                            <RankingTable />
                        </div>
                    </div>
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('基金经理')}
                    <div className={`mt_20`}>
                        <ManagerList />
                    </div>
                </div>

                <div className={`${ProductStyle.charts_item_bg} mt_20`}>
                    {this.noCheckHeader('同机构产品')}
                    <div className='product_table_pt'>
                        <HomeTable />
                    </div>
                </div> */}

                <AddModal ref='addModals' />
            </div>
        )
    }
}

